package Demo;


import java.util.PriorityQueue;

public class Demo01 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(1000);
            }
        }, 1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(3000);
            }
        }, 3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println(2000);
            }
        }, 2000);
    }
}

class MyTimerTask implements Comparable<MyTimerTask> {
    //执行的任务
    private Runnable runnable;
    //执行任务的时间
    private long time;

    MyTimerTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+time;
    }

    public int compareTo(MyTimerTask o2) {
        return (int) (this.time - o2.time);
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

class MyTimer {
    //使用优先级队列, 每次都先拿出最小时间的任务
    PriorityQueue<MyTimerTask> p = new PriorityQueue<>();
    Object locker = new Object();

    MyTimer() {
        Thread t = new Thread(() -> {
            while(true) {
                synchronized (locker) {
                    while (p.isEmpty()) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    long currentTimes = System.currentTimeMillis();
                    MyTimerTask min = p.peek();
                    if (currentTimes >= min.getTime()) {
                        min.getRunnable().run();
                        p.poll();
                    } else {
                        try {
                            locker.wait(min.getTime() - currentTimes);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }

        });
        t.start();
    }

    public void schedule(Runnable runnable, long time) {
        synchronized (locker) {
            p.offer(new MyTimerTask(runnable, time));
            locker.notify();
        }

    }
}

